#include "Window.h"

using namespace fe;


Window::Window(uint16 w, uint16 h, uint16 bpp, std::string title, bool fullscreen)
    :
    m_width(w), m_height(h), m_bpp(bpp), m_title(title), m_fullscreen(fullscreen)
{
    m_open = true;
    SDL_Init(SDL_INIT_VIDEO);

    SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

    // Set the title.
    SDL_WM_SetCaption(title.c_str(), title.c_str());

    int flags = SDL_OPENGL;
    if(fullscreen == true)
    {
            flags |= SDL_FULLSCREEN;
    }

    m_screen = SDL_SetVideoMode( m_width, m_height, m_bpp, flags );

    SDL_Event resizeEvent;
    resizeEvent.type = SDL_VIDEORESIZE;
    resizeEvent.resize.w = m_width;
    resizeEvent.resize.h = m_height;
    SDL_PushEvent(&resizeEvent);

    initGL();
}

Window::~Window()
{
    SDL_FreeSurface(m_screen);
    SDL_Quit();
}


void Window::initGL()
{
    glEnable(GL_BLEND);
    glBlendFunc(GL_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glEnable(GL_TEXTURE_2D);

    glDisable(GL_DEPTH_TEST); // for transparent colors

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    glOrtho(0,m_width, m_height,0,-1,1);		// Orthographic projection
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    glClearColor(0.0, 0.0, 0.0, 0.0);
}

void Window::setSize(uint16 w, uint16 h)
{
    m_width = w;
    m_height = h;

    SDL_Event resize;
    resize.type = SDL_VIDEORESIZE;

    resize.resize.w = m_width;
    resize.resize.h = m_height;

    SDL_PushEvent(&resize);
}


void Window::close()
{
    m_open = false;
}
